<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<link rel="stylesheet" href="/plug-in/layui/css/layui.css" media="all">
<script src="/plug-in/layui/layui.js"></script>
<script>
var uploadFn = {
	filetype: '.jpg|.gif|.png|.txt|.rar|.zip|.doc|.docx|.xls|.xlsx|.pdf|.jpeg',
	jq: null,
	readonly:false,
	uploadUrl: 	'/console/layui/upload/',
	uploadDeleteUrl:'/console/layui/upload/delete',
	uploadListUrl:'/console/layui/upload/list',
	/*
	*附件下载
	*/
	down: function(id,name){
		this.openWindowInHidden({ url: '/console/download?id='+ id });
	},
	/*
	*删除附件
	*/
	deleteFn: function(fileId,fileName,index){
		var _this = this;
		if(fileId){
			$.messager.confirm('确认','您确认想要删除附件【'+ fileName +'】吗？',function(r){    
			    if (r){    
			    	$.post(_this.uploadDeleteUrl,{id: fileId || ''},function(result){
						if(result.flag == true){
							layer.tips('删除成功!', '#layUpload',{tips: [1, '#009688'], time: 1000});
							_this.removeRow(index);
							_this.setValue();
						}else{
							layer.tips('删除异常!', '#layUpload',{tips: [1, '#009688'], time: 1000});
						}
					});    
			    }    
			});
		}else{
			_this.removeRow(index);
		}
	},
	/*
	删除行
	*/
	removeRow: function(index){
		$('#dg').datagrid('deleteRow',index);
	},
	appendRow: function(row){
		$('#dg').datagrid('appendRow',row);
	},
	listFn:function(fileIds){
		var _this = this;
		$.post(this.uploadListUrl,{ids: fileIds},function(result){
			$.each(result || [], function (index, node) {
				node.name = node.original;
				uploadFn.appendRow(node);
            });
		});
	},
	openWindowInHidden: function (opts) {
		opts = $.extend({
			url: '',
			method: 'POST',
			target: '',
			queryParams: {}
		}, opts);
		if (!opts.url) return;
		if (!opts.target && 0 >= $('#hideFrameOfOpenWindow').length) {
			$('<iframe id="hideFrameOfOpenWindow" name="hideFrameOfOpenWindow"></iframe>').hide().appendTo(document.body);
		}
		if ((opts.method || '').toUpperCase() === 'GET') {
			var url = opts.url || '', params = $.isPlainObject(opts.queryParams) ? $.param(opts.queryParams, true) : opts.queryParams;
			if (!!params) url += (0 > url.indexOf('?') ? '?' : '&') + params;
			window.open(url, !!opts.target && opts.target || 'hideFrameOfOpenWindow');
		} else {
			var $form = $('#hideFormOfOpenWindow'), val;
			if (0 >= $form.length) {
				$form = $('<form id="hideFormOfOpenWindow" method="post" target="hideFrameOfOpenWindow"></form>');
				$form.hide().appendTo(document.body);
			}
			!!opts.target && $form.attr('target', opts.target);
			$form.empty();
			createHidden('', opts.queryParams);
			$form.attr('action', opts.url);
			$form[0].submit();
			function createHidden(key, val) {
				if (!!key && (val === undefined || val === null)) {
					$('<input type="hidden"/>').attr('name', key).appendTo($form);
				} else if ($.isArray(val)) {
					$.each(val, function () {
						createHidden(key, this);
					});
				} else if ($.isPlainObject(val)) {
					for (var name in val) {
						createHidden((!!key && (key + '.') || '') + name, val[name]);
					}
				} else if (!!key && !$.isFunction(val)) {
					$('<input type="hidden"/>').attr('name', key).val(val).appendTo($form);
				}
			}
		}
	},
	/*设置列表id*/
	setValue: function(){
		var jq = this.jq;
		var fileId = [];
		var rows = $("#dg").datagrid('getData').rows;
		$.each(rows,function(index,row){
			if(row.id){ fileId.push(row.id);}
		});
		fileId = fileId.join(",");
		jq.textbox('setValue',fileId);
	},
	/*通过属性获取行索引*/
	getGridIndex: function(filedName,filedVal){
        var rowindex  = -1;  
		var rows = $("#dg").datagrid('getData').rows;  
        var length = rows.length;
        for (var i = 0,len=rows.length;i < len; i++) {  
            if (rows[i][filedName] == filedVal) {
                rowindex = i;  
                break;  
            }  
        }
       return rowindex;
	},
	sizeFormart: function(size){
		var sizeType = (typeof size =='number') ;
		if(sizeType){
			if(size>=0 && size<1048576){
				size = (size/1024).toFixed(1) + "KB";
			}else{
				size = (size/1048576).toFixed(1) + "MB";
			}
		}
		return size;
	}
};

$.parser.plugins.push("layuiupload");//注册扩展组件
$.fn.layuiupload = function (options, param) {//定义扩展组件
    //当options为字符串时，说明执行的是该插件的方法。
    if (typeof options == "string") { return $.fn.textbox.apply(this, arguments); }
    options = options || {};
    //当该组件在一个页面出现多次时，this是一个集合，故需要通过each遍历。
    return this.each(function () {
        var jq = $(this) , jqName = jq.attr("name") || jq.attr("id");
        //echo属性控制是否异步加载回显数据
        var myopts = $.extend({}, $.fn.textbox.parseOptions(this), options);
        $.fn.textbox.call(jq, myopts);
        
        uploadFn.jq = jq;
        var uploadP = myopts.upload || {};
        /*控件初始化及回显*/        
        setTimeout(function(){
        	uploadFn.readonly = uploadP.readonly || false;
			initUploadifybox();
        },100);
        
	    /*添加uploadify控件目标*/
        function initUploadifybox(){
	    	var height = uploadP.height || 200;
        	var uploadifybox = '<div style="width:100%;heigth:400px;"><div id="dg" style="width:100%;height:'+ height +'px;"></div></div>' ;
	        var textbox =  jq.parent().find(".textbox").css("border","0px");
	        textbox.find(".textbox-text").hide();
	        textbox.append(uploadifybox);
	        
	        var toolbar = [];
	        if(uploadP.auto==true){
	        	toolbar = [
	   	                { text:'文件选择',id:'layUpload',iconCls: 'icon-search'}
		        	];
	        }else{
	        	toolbar = [
   	                { text:'文件选择',id:'layUpload',iconCls: 'icon-search'},
	        		'-',
	        		{ text:'开始上传', id:'uploadAction', iconCls: 'icon-ok'}
	        	];
	        }
	        if(uploadP.readonly==true){
	        	toolbar = [];
	        }
	        
	        $('#dg').datagrid({    
	        	fitColumns:true,
	        	singleSelect:true,
	            columns:[[    
	                {field:'id',title:'主键',hidden:true,formatter:function(value,row,index){
	                	value = value || '';
	                	return '<a fileid="'+ value +'" href="#" ></a>';
	                }},    
	                {field:'findex',title:'索引',hidden:true},    
	                {field:'type',title:'文件类型',width:100,formatter:function(value,row,index){
	                	var filetype = uploadFn.filetype;
	                	value= (value || '.other' ).toLowerCase();
	                	if(filetype.indexOf(value)>=0){
	                		value = value.substring(1);
	                		return '<img src="/images/file_'+ value+'.png"  alt="" />'
	                	}else{
	                		return '<img src="/images/file_other.png"  alt="" />'
	                	}
	                }},  
	                {field:'name',title:'文件名',width:300,formatter:function(value,row,index){
	                	var html = []; html.push('<p title="'+ value +'">'+ value + '</p>');
	                	html.push('<p title="'+ value +'">'+ uploadFn.sizeFormart(row.size) + '</p>');
	                	return html.join('');
	                }},  
	                {field:'state',title:'状态',width:80},
	                {field:'opt',title:'操作',width:100,formatter:function(value,row,index){
	                	var hrefs = [];
	                	var downA = "<a class='fileopt' title='下载'  onclick=\"uploadFn.down(\'"+ (row.id || '') +"\',\'" + row.name + "\',"+  index +")\" href='javascript:void(0)'>下载</a>";
	                	var delA = "<a class='fileopt'  title='删除'   onclick=\"uploadFn.deleteFn(\'"+ (row.id || '') +"\',\'" + row.name + "\',"+  index +")\" href='javascript:void(0)'>删除</a>";
	                	hrefs.push(downA);	hrefs.push(delA);
	                	if(uploadFn.readonly){
	                		return downA;
	                	}else{
			    			return hrefs.join("&nbsp;&nbsp;&nbsp;");
	                	}
	                }}
	            ]],
	            toolbar: toolbar
	        });  
	        
	        layui.use('upload', function(){
				  var upload = layui.upload;
				  var files = null;
				  //多文件列表示例
				  var demoListView = $('#demoList');
				  var uploadOpt = {
			    	elem: '#layUpload'
				    ,url: uploadFn.uploadUrl
				    ,accept: 'file'
				    ,multiple: true
				    ,auto: false
				    ,bindAction: '#uploadAction'
			    	,before: function(obj){ //obj参数包含的信息，跟 choose回调完全一致，可参见上文。
			    		var upList = $("a[fileid='']"),upLen = upList.length;
			    		if(upLen>0){
				    	    layer.load(); //上传loading
			    		}else{
			    			layer.tips('请选择待上传文件!', '#layUpload',{tips: [1, '#009688'], time: 1000});
			    		}
			    	}
				    ,choose: function(obj){
					    files = obj.pushFile(); //将每次选择的文件追加到文件队列
					      //读取本地文件
					      obj.preview(function(findex, file, result){
					    	  var fileName = file.name;
					    	  var index1=fileName.lastIndexOf(".");
					    	  var index2=fileName.length;
					    	  var suffix=fileName.substring(index1,index2);//后缀名
					    	  uploadFn.appendRow({
					    		    type: suffix,
					        	    findex: findex,
					        		name: file.name,
					        		size: file.size,
					        		state: '待上传'
					          });
					      });
				    }
				    ,done: function(res, findex, upload){
				    	  layer.closeAll('loading');
					      if(res.flag == true){ //上传成功
								var index = uploadFn.getGridIndex('findex',findex);//获取上传成功行索引
								if(index==-1){
									res.data.name = res.data.original;
									uploadFn.appendRow(res.data);
								}else{
									$('#dg').datagrid('updateRow',{
								      	index: index,
								    	row: { state: res.data.state || '', id: res.data.id }
								    });
								}
							    //删除上传成功文件队列
							    if(files){ delete files[findex]; }
					      }else{
						  	this.error(findex, upload);
					      }
					      uploadFn.setValue();
				    }
				    ,error: function(findex, upload){
				    	 layer.closeAll('loading');
				    	 var index = uploadFn.getGridIndex('findex',findex);//获取上传成功行索引
				    	  $('#dg').datagrid('updateRow',{
				    		    index: index,
				    			row: { state: '上传失败！'}
				    	  });
				    }
				};
				uploadOpt = $.extend(true,uploadOpt, uploadP);
				upload.render(uploadOpt);
				/*数据回显*/
				setTimeout(function(){
					//console.log('数据延迟回显');
					uploadFn.listFn(jq.textbox('getValue'));
				},500);
			});
        }
    });
};
</script>